﻿using System;
using System.Linq;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;

namespace TfsWrapper.Commands
{
    public class FindMentionsByChangesetCommand : TfsCommand
    {
        private readonly IOutputPrinter<IssueMention> printer;

        public FindMentionsByChangesetCommand(IOutputPrinter<IssueMention> printer)
        {
            this.printer = printer;
        }

        public override void Execute(TfsConnection tfs, params string[] args)
        {
            if(args.Count() > 1)
                throw new InvalidOperationException(string.Format("Command {0} does not support more than one argument, which is the ID of the changeset", GetType().Name));

            var vcs = tfs.GetService<VersionControlServer>();

            int changesetId;

            if (int.TryParse(args.Single(), out changesetId) == false)
            {
                // it might be a shelveset used by TC in pre-tested commits,
                // and it can't have any issue associated to it
                return;
            }

            Changeset changeset;

            try
            {
                changeset = vcs.GetChangeset(changesetId);
            }
            catch (ChangesetNotFoundException)
            {
                return;
            }
            catch (ResourceAccessException)
            {
                return;
            }

            var mentions = from workItem in 
                           changeset.WorkItems
                           select new IssueMention {Id = workItem.Id.ToString(), Url = MakeWorkItemUrl(tfs, workItem)};

            foreach (var mention in mentions)
            {
                printer.Print(mention);
                printer.PrintNewLine();
            }
        }
    }
}